import 'package:dio/dio.dart';
import 'interceptor/log_interceptor.dart';
import 'interceptor/rest_api_interceptor.dart';
import 'service_config.dart';

/// Dio 工厂类：按服务名创建并缓存独立的 Dio 实例
class DioFactory {
  // 缓存不同服务的 Dio 实例
  static final Map<String, Dio> _instances = {};

  /// 获取指定服务的 Dio 实例
  static Dio getInstance(String serviceName) {
    if (_instances.containsKey(serviceName)) {
      return _instances[serviceName]!;
    }

    final dio = _createDio(serviceName);
    _instances[serviceName] = dio;
    return dio;
  }

  /// 创建并初始化 Dio
  static Dio _createDio(String serviceName) {
    final baseUrl = ServiceConfig.getBaseUrl(serviceName);

    final dio = Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      responseType: ResponseType.json,
    ));
    // 序列化响应
    dio.interceptors.add(RestApiInterceptor());
    // 日志拦截器
    dio.interceptors.add(PrintLogInterceptor());

    return dio;
  }
}
